﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;
using DiagramDesigner.Common.Controls;

namespace Behavior.Drag
{
    public class DragBehavior : Behavior<DesignerItem>
    {
        private RotateTransform _rotateTransform;
        private Point? _startPosition;
        private readonly TranslateTransform transform = new TranslateTransform();
        private DesignerCanvas _canvas;

        protected override void OnAttached()
        {
            AssociatedObject.MouseMove += AssociatedObjectOnMouseMove;
            AssociatedObject.MouseLeftButtonDown += AssociatedObjectOnMouseLeftButtonDown;
            AssociatedObject.MouseLeftButtonUp += AssociatedObjectOnMouseLeftButtonUp;
        }

        private void AssociatedObjectOnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (AssociatedObject.IsMouseCaptured) AssociatedObject.ReleaseMouseCapture();
            _startPosition = null;

        }

        private void AssociatedObjectOnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _canvas = VisualTreeHelper.GetParent(AssociatedObject) as DesignerCanvas;
            if (_canvas == null) return;
            _rotateTransform = AssociatedObject.RenderTransform as RotateTransform;
            _startPosition = e.GetPosition(_canvas);
        }

        private void AssociatedObjectOnMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && _startPosition.HasValue)
            {
                if (!AssociatedObject.IsMouseCaptured) AssociatedObject.CaptureMouse();
                Point position = e.GetPosition(_canvas);
                Canvas.SetLeft(AssociatedObject, position.X - AssociatedObject.Width / 2);
                Canvas.SetTop(AssociatedObject, position.Y - AssociatedObject.Height / 2);
                _canvas.InvalidateMeasure();
            }
        }
    }
}
